{
 "cells": [
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "#（1）导入相关库，读取“广州二手房价.csv”数据，合并“region”与“positionInfo”列数据，\n",
    "# 并新建“region_positionInfo”列用于保存；去除“'unitPrice'”列数据存在的特殊符号“，”。"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-04-28T03:47:43.645662Z",
     "start_time": "2024-04-28T03:47:43.631120Z"
    }
   },
   "id": "1f7aeebc646dba5",
   "execution_count": 2
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2024-04-28T03:47:52.422660Z",
     "start_time": "2024-04-28T03:47:43.648151Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.preprocessing import StandardScaler, MinMaxScaler\n",
    "from sklearn.feature_selection import mutual_info_classif\n",
    "from sklearn.ensemble import RandomForestRegressor\n",
    "from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error\n",
    "from sklearn.model_selection import train_test_split"
   ]
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "   shi  ting region    area  toward  renovation  construction_time  floor  \\\n0    3     2    天河区  119.79       1           4               18.0     19   \n1    4     2    天河区  234.54       1           4               15.0     45   \n2    2     1    天河区   73.70       2           3               20.0     19   \n3    3     2    天河区   90.67       2           3               16.0      9   \n4    3     2    天河区  123.13       2           4               15.0     14   \n\n   architectural_form positionInfo  totalPrice unitPrice region_positionInfo  \n0                   2     天誉华庭-龙口西      1320.0    110193        天河区_天誉华庭-龙口西  \n1                   3     誉峰-珠江新城东      4150.0    176943        天河区_誉峰-珠江新城东  \n2                   1       汇友苑-东圃       338.0     45862          天河区_汇友苑-东圃  \n3                   1      橡树园-沙太南       370.0     40808         天河区_橡树园-沙太南  \n4                   1    珠江俊园-华景新城       843.0     68435       天河区_珠江俊园-华景新城  ",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>shi</th>\n      <th>ting</th>\n      <th>region</th>\n      <th>area</th>\n      <th>toward</th>\n      <th>renovation</th>\n      <th>construction_time</th>\n      <th>floor</th>\n      <th>architectural_form</th>\n      <th>positionInfo</th>\n      <th>totalPrice</th>\n      <th>unitPrice</th>\n      <th>region_positionInfo</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>3</td>\n      <td>2</td>\n      <td>天河区</td>\n      <td>119.79</td>\n      <td>1</td>\n      <td>4</td>\n      <td>18.0</td>\n      <td>19</td>\n      <td>2</td>\n      <td>天誉华庭-龙口西</td>\n      <td>1320.0</td>\n      <td>110193</td>\n      <td>天河区_天誉华庭-龙口西</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>4</td>\n      <td>2</td>\n      <td>天河区</td>\n      <td>234.54</td>\n      <td>1</td>\n      <td>4</td>\n      <td>15.0</td>\n      <td>45</td>\n      <td>3</td>\n      <td>誉峰-珠江新城东</td>\n      <td>4150.0</td>\n      <td>176943</td>\n      <td>天河区_誉峰-珠江新城东</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2</td>\n      <td>1</td>\n      <td>天河区</td>\n      <td>73.70</td>\n      <td>2</td>\n      <td>3</td>\n      <td>20.0</td>\n      <td>19</td>\n      <td>1</td>\n      <td>汇友苑-东圃</td>\n      <td>338.0</td>\n      <td>45862</td>\n      <td>天河区_汇友苑-东圃</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>3</td>\n      <td>2</td>\n      <td>天河区</td>\n      <td>90.67</td>\n      <td>2</td>\n      <td>3</td>\n      <td>16.0</td>\n      <td>9</td>\n      <td>1</td>\n      <td>橡树园-沙太南</td>\n      <td>370.0</td>\n      <td>40808</td>\n      <td>天河区_橡树园-沙太南</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>3</td>\n      <td>2</td>\n      <td>天河区</td>\n      <td>123.13</td>\n      <td>2</td>\n      <td>4</td>\n      <td>15.0</td>\n      <td>14</td>\n      <td>1</td>\n      <td>珠江俊园-华景新城</td>\n      <td>843.0</td>\n      <td>68435</td>\n      <td>天河区_珠江俊园-华景新城</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df = pd.read_csv('./广州二手房价.csv')\n",
    "df['region_positionInfo'] = df['region'] + '_' + df['positionInfo']\n",
    "df['unitPrice'] = df['unitPrice'].str.replace(',', '')\n",
    "df.head()"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-04-28T04:07:08.075852Z",
     "start_time": "2024-04-28T04:07:07.996933Z"
    }
   },
   "id": "8816835fd4510a0d",
   "execution_count": 12
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "# （2）将新建的“region_positionInfo”列数据进行数值型编码，并删除原来的“region”与“positionInfo”列数据。1"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-04-28T03:47:52.593283Z",
     "start_time": "2024-04-28T03:47:52.580760Z"
    }
   },
   "id": "bc5dc2f47c41bde6",
   "execution_count": 5
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "   shi  ting    area  toward  renovation  construction_time  floor  \\\n0    3     2  119.79       1           4               18.0     19   \n1    4     2  234.54       1           4               15.0     45   \n2    2     1   73.70       2           3               20.0     19   \n3    3     2   90.67       2           3               16.0      9   \n4    3     2  123.13       2           4               15.0     14   \n\n   architectural_form  totalPrice unitPrice  region_positionInfo  \n0                   2      1320.0    110193                24893  \n1                   3      4150.0    176943                21497  \n2                   1       338.0     45862                 7491  \n3                   1       370.0     40808                10181  \n4                   1       843.0     68435                 2216  ",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>shi</th>\n      <th>ting</th>\n      <th>area</th>\n      <th>toward</th>\n      <th>renovation</th>\n      <th>construction_time</th>\n      <th>floor</th>\n      <th>architectural_form</th>\n      <th>totalPrice</th>\n      <th>unitPrice</th>\n      <th>region_positionInfo</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>3</td>\n      <td>2</td>\n      <td>119.79</td>\n      <td>1</td>\n      <td>4</td>\n      <td>18.0</td>\n      <td>19</td>\n      <td>2</td>\n      <td>1320.0</td>\n      <td>110193</td>\n      <td>24893</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>4</td>\n      <td>2</td>\n      <td>234.54</td>\n      <td>1</td>\n      <td>4</td>\n      <td>15.0</td>\n      <td>45</td>\n      <td>3</td>\n      <td>4150.0</td>\n      <td>176943</td>\n      <td>21497</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>2</td>\n      <td>1</td>\n      <td>73.70</td>\n      <td>2</td>\n      <td>3</td>\n      <td>20.0</td>\n      <td>19</td>\n      <td>1</td>\n      <td>338.0</td>\n      <td>45862</td>\n      <td>7491</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>3</td>\n      <td>2</td>\n      <td>90.67</td>\n      <td>2</td>\n      <td>3</td>\n      <td>16.0</td>\n      <td>9</td>\n      <td>1</td>\n      <td>370.0</td>\n      <td>40808</td>\n      <td>10181</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>3</td>\n      <td>2</td>\n      <td>123.13</td>\n      <td>2</td>\n      <td>4</td>\n      <td>15.0</td>\n      <td>14</td>\n      <td>1</td>\n      <td>843.0</td>\n      <td>68435</td>\n      <td>2216</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df1 = df.loc[:, ('unitPrice', 'region_positionInfo')]\n",
    "\n",
    "df2 = df1.sort_values(by='unitPrice', ascending=False)\n",
    "region_positionInfo = df2['region_positionInfo']\n",
    "\n",
    "region_positionInfo_dict = {}\n",
    "\n",
    "for n, i in enumerate(region_positionInfo):\n",
    "    region_positionInfo_dict[i] = n + 1\n",
    "\n",
    "df[\"region_positionInfo\"] = df['region_positionInfo'].map(region_positionInfo_dict)\n",
    "\n",
    "# 删除原字段\n",
    "# df.drop(['region','positionInfo'],axis=1,inplace=True)\n",
    "df.head()"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-04-28T04:13:29.307380Z",
     "start_time": "2024-04-28T04:13:29.257605Z"
    }
   },
   "id": "b05c5d48737a5929",
   "execution_count": 27
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "        shi      ting      area    toward  renovation  construction_time  \\\n0  0.333333  0.333333  0.096064  0.000000    1.000000           0.333333   \n1  0.444444  0.333333  0.194363  0.000000    1.000000           0.274510   \n2  0.222222  0.166667  0.056581  0.142857    0.666667           0.372549   \n3  0.333333  0.333333  0.071118  0.142857    0.666667           0.294118   \n4  0.333333  0.333333  0.098925  0.142857    1.000000           0.274510   \n\n      floor  architectural_form  unitPrice  region_positionInfo  \n0  0.327586                0.25   0.539743             0.982199  \n1  0.775862                0.50   0.882089             0.848155  \n2  0.327586                0.00   0.209803             0.295323  \n3  0.155172                0.00   0.183882             0.401500  \n4  0.241379                0.00   0.325575             0.087113  ",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>shi</th>\n      <th>ting</th>\n      <th>area</th>\n      <th>toward</th>\n      <th>renovation</th>\n      <th>construction_time</th>\n      <th>floor</th>\n      <th>architectural_form</th>\n      <th>unitPrice</th>\n      <th>region_positionInfo</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>0.333333</td>\n      <td>0.333333</td>\n      <td>0.096064</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n      <td>0.333333</td>\n      <td>0.327586</td>\n      <td>0.25</td>\n      <td>0.539743</td>\n      <td>0.982199</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>0.444444</td>\n      <td>0.333333</td>\n      <td>0.194363</td>\n      <td>0.000000</td>\n      <td>1.000000</td>\n      <td>0.274510</td>\n      <td>0.775862</td>\n      <td>0.50</td>\n      <td>0.882089</td>\n      <td>0.848155</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>0.222222</td>\n      <td>0.166667</td>\n      <td>0.056581</td>\n      <td>0.142857</td>\n      <td>0.666667</td>\n      <td>0.372549</td>\n      <td>0.327586</td>\n      <td>0.00</td>\n      <td>0.209803</td>\n      <td>0.295323</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>0.333333</td>\n      <td>0.333333</td>\n      <td>0.071118</td>\n      <td>0.142857</td>\n      <td>0.666667</td>\n      <td>0.294118</td>\n      <td>0.155172</td>\n      <td>0.00</td>\n      <td>0.183882</td>\n      <td>0.401500</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>0.333333</td>\n      <td>0.333333</td>\n      <td>0.098925</td>\n      <td>0.142857</td>\n      <td>1.000000</td>\n      <td>0.274510</td>\n      <td>0.241379</td>\n      <td>0.00</td>\n      <td>0.325575</td>\n      <td>0.087113</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = df.drop('totalPrice', axis=1)\n",
    "y = df['totalPrice']\n",
    "\n",
    "mm = MinMaxScaler()\n",
    "data = mm.fit_transform(X)\n",
    "\n",
    "X = pd.DataFrame(data, columns=X.columns.tolist())\n",
    "X.head()"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-04-28T04:15:09.117278Z",
     "start_time": "2024-04-28T04:15:09.050880Z"
    }
   },
   "id": "a87158430c35501e",
   "execution_count": 28
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "                     importance\nunitPrice              0.793140\nregion_positionInfo    0.658498\narea                   0.411739\nshi                    0.275983\nting                   0.245694\nconstruction_time      0.187198\nrenovation             0.157796\nfloor                  0.136928\ntoward                 0.055254\narchitectural_form     0.034315",
      "text/html": "<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>importance</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>unitPrice</th>\n      <td>0.793140</td>\n    </tr>\n    <tr>\n      <th>region_positionInfo</th>\n      <td>0.658498</td>\n    </tr>\n    <tr>\n      <th>area</th>\n      <td>0.411739</td>\n    </tr>\n    <tr>\n      <th>shi</th>\n      <td>0.275983</td>\n    </tr>\n    <tr>\n      <th>ting</th>\n      <td>0.245694</td>\n    </tr>\n    <tr>\n      <th>construction_time</th>\n      <td>0.187198</td>\n    </tr>\n    <tr>\n      <th>renovation</th>\n      <td>0.157796</td>\n    </tr>\n    <tr>\n      <th>floor</th>\n      <td>0.136928</td>\n    </tr>\n    <tr>\n      <th>toward</th>\n      <td>0.055254</td>\n    </tr>\n    <tr>\n      <th>architectural_form</th>\n      <td>0.034315</td>\n    </tr>\n  </tbody>\n</table>\n</div>"
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 划分数据\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=4)\n",
    "y = y.astype('int')\n",
    "imp = pd.DataFrame(mutual_info_classif(X_train, y_train), index=X.columns)\n",
    "\n",
    "imp.columns = ['importance']\n",
    "imp.sort_values(by='importance', ascending=False)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-04-28T05:57:16.150346Z",
     "start_time": "2024-04-28T05:57:05.596685Z"
    }
   },
   "id": "968ed949d96d8eb6",
   "execution_count": 31
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "training score 0.998846986227883\n"
     ]
    }
   ],
   "source": [
    "# 随机森林回归模型\n",
    "rfr = RandomForestRegressor()\n",
    "model = rfr.fit(X_train, y_train)\n",
    "# 训练得分\n",
    "print('training score', model.score(X_train, y_train))\n",
    "# 预测值\n",
    "predictions = model.predict(X_test)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-04-28T06:08:59.032138Z",
     "start_time": "2024-04-28T06:08:40.824515Z"
    }
   },
   "id": "a35f86d0ab82f6e4",
   "execution_count": 33
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "r2_score 0.9917383412117583\n"
     ]
    }
   ],
   "source": [
    "r2 = r2_score(y_test, predictions)\n",
    "print(\"r2_score\", r2)\n"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-04-28T06:10:10.802898Z",
     "start_time": "2024-04-28T06:10:10.796807Z"
    }
   },
   "id": "da1d64e9df63433f",
   "execution_count": 37
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MAE 3.743722627737226\n",
      "MSE 1178.0992717498523\n",
      "RMSE 34.323450755275935\n"
     ]
    }
   ],
   "source": [
    "print('MAE', mean_absolute_error(y_test, predictions))\n",
    "print('MSE', mean_squared_error(y_test, predictions))\n",
    "print(\"RMSE\", np.sqrt(mean_squared_error(y_test, predictions)))"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-04-28T06:11:06.711132Z",
     "start_time": "2024-04-28T06:11:06.701577Z"
    }
   },
   "id": "a2c2969d6551b334",
   "execution_count": 38
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
